<?php

require 'vars.php';
require 'functs.php';
require 'config.install.php';

if ($installed != '1') {
	include 'install.php';
	die;
}
elseif (is_writable('config.install.php') || is_writable('config.mysql.php')) {
	die ("One of the config files is still writable by the webserver.<br />See README for details.");
}

Authenticate();

require 'config.mysql.php';

header("Cache-Control: no-cache");
Page_startup($title,$version);
Page_headbar($_SESSION[user],Get_timesettings($_SESSION[user],$mysql_server,$mysql_user,$mysql_pass,$mysql_db));

$link = mysql_connect($mysql_server,$mysql_user,$mysql_pass) or die('Unable to connect to MySQL server: ' . mysql_error());
mysql_select_db($mysql_db,$link) or die ('Can\'t use db: ' . mysql_error());

$name = mysql_real_escape_string($_SESSION[user]);
	
$lastseen = time();
$lastseen = mysql_real_escape_string($lastseen);
$lastseensql = "UPDATE `featherchat_users` SET `lastseen` = '".$lastseen."' WHERE `name` = '".$name."'"  ;
mysql_query($lastseensql) or die ("Unable to update 'lastseen' time in database");
	
?>
<table cellspacing="0">
	<?php
	
	$name = mysql_real_escape_string($_SESSION[user]);

	$getcountsql = "SELECT `history` FROM `featherchat_users` WHERE `name` = '".$name."'";
	$result = mysql_query($getcountsql);
	$getcount = mysql_result($result,0) or die ("Unable to retrieve user's history setting.");
	
	$lowestidstring = "SELECT `msgid` FROM `featherchat_messages` ORDER BY `msgid` ASC LIMIT 1";
	$result = mysql_query($lowestidstring);
	$lowestid = @mysql_result($result,0); // Don't error here; a fresh install has 0 posts.
	
	// We need to know the number of actual rows, not just the highest msgid...
	$rowcountsql = 'SELECT `msgid` FROM `featherchat_messages`;';
	$result = mysql_query($rowcountsql);
	$rowcount = mysql_num_rows($result);

	// Get the most recent post from any user.
	$mostrecentsql = "SELECT `msgid` FROM `featherchat_messages` ORDER BY `msgid` DESC LIMIT 1";
	$result = mysql_query($mostrecentsql);
	$mostrecentbyid = @mysql_result($result,0); // no error when there are 0 posts, please...

	if (!isset($_GET[show])) {
	
		if ($getcount != 101) { // This is for users who have set a particular number for their history option.
	
			if ($getcount > $rowcount) { $getcount = $rowcount; }
			$i2 = $getcount;

			if ($rowcount-$i2<0) { $i2 = $lowestid; } // So we don't search for rows that don't exist... ex. LIMIT -4,12
			
			$firstshown = ($rowcount-$i2); // For the 'previous' button.
			
			$i=1;
			while ($i <= $getcount) {
	
				$sendstring = "SELECT * FROM `featherchat_messages` ORDER BY `msgid` ASC LIMIT ".($rowcount-$i2).",".$rowcount;
				$result = mysql_query($sendstring) or die ("Unable to retrieve messages!");
				$msg_r = mysql_fetch_assoc($result);

				if (!empty($msg_r)) {
					Message_print($msg_r,$_SESSION[user],$i,$getcount);
				}
	
				$i++;
				$i2--;
			} 
		}
		else {	// This is for users who have set 'since my last post' as their history option.

			// Get the user's most recent post.
			$mymostrecentsql = "SELECT `msgid` FROM `featherchat_messages` WHERE `user` = '".$name."' ORDER BY `msgid` DESC LIMIT 1";
			$result = mysql_query($mymostrecentsql);
			$mymostrecent = mysql_result($result,0);

			// What's the fewest number of posts the user wants to see?
			$histminsql = "SELECT `histmin` FROM `featherchat_users` WHERE `name` = '".$name."'";
			$result = mysql_query($histminsql);
			$histmin = mysql_result($result,0);

			// How many posts by other users since this user's last post?
			$rowdiffsql = "SELECT `msgid` FROM `featherchat_messages` WHERE `msgid` >= ".$mymostrecent." AND `msgid` <= ".$mostrecentbyid;
			$result = mysql_query($rowdiffsql);
			$rowdiff = mysql_num_rows($result);

			// If the user's minimum posts to show setting is higher than the number of posts since his most recent, show the number he has set; otherwise show all since his last post.
			if ($histmin > $rowdiff) {
				$count = $histmin;
			} else { $count = $rowdiff; }

			$i=0;
			$i2=$count;

			if ($rowcount-$i2<0) { $i2 = abs($rowcount-$i2)+2; } // So we don't search for rows that don't exist... ex. LIMIT -4,12
			
			$firstshown = ($rowcount-$i2); // For the 'previous' button.
			
			while ($i < $count) {
				$getmessagessql = "SELECT * FROM `featherchat_messages` ORDER BY `msgid` ASC LIMIT ".($rowcount-$i2).",1";
				$result = mysql_query($getmessagessql);
				$msg_r = mysql_fetch_assoc($result);

				if (!empty($msg_r)) {
					Message_print($msg_r,$_SESSION[user],$i,$rowdiff+1);
				}

				$i++;
				$i2--;
			}
		}
	}
	else { // This is for scrolling back in the history.

		if ($getcount != 101) {
			$numbertoshow = $getcount;
		}
		else {
			// What's the fewest number of posts the user wants to see?
			$histminsql = "SELECT `histmin` FROM `featherchat_users` WHERE `name` = '".$name."'";
			$result = mysql_query($histminsql);
			$histmin = mysql_result($result,0);
			$numbertoshow = $histmin;
		}

		$firstshown = ($_GET[show] - $numbertoshow);

		$i=0;
		while ($i < $numbertoshow) {
		
			if ($firstshown < 0) { // So we don't search below row 0;
				$firstshown=(abs($firstshown)+($firstshown));
			}
			if ($firstshown == 0) { $hideprevbutton = 1; }
	
			$sendstring = "SELECT * FROM `featherchat_messages` ORDER BY `msgid` ASC LIMIT ".($firstshown+$i).",1";
			$result = mysql_query($sendstring) or die ("Unable to retrieve messages!");
			$msg_r = mysql_fetch_assoc($result);

			if (!empty($msg_r)) {
				Message_print($msg_r,$_SESSION[user],$i,$getcount);
			}

			if ($i+1 == $numbertoshow) { // This section determines whether or not to show the 'refresh' and 'next' buttons
				if ($firstshown+$i+1 < $rowcount) {
					$shownextbutton = 1;
				}
				else {
					$shownextbutton = 0;
					$showrefreshbutton = 1;
				}
			}

			$i++;
		}
	}
	
	echo "\n"; ?><tr><td colspan="3">

	<form method="post" action="sent.php">
	<input type="textbox" size="30" name="msg" />
	<input type="submit" value="Send" /> <?php
	if ((!isset($_GET[show])) || $showrefreshbutton == 1) { ?>| <a href="javascript:location.href='index.php';">Refresh</a> <?php }
	if ($hideprevbutton != 1) { ?>| <a href="index.php?show=<?php echo $firstshown; ?>"><</a> <?php }
	
	// Here we display the forward button only if there are posts higher than those displayed
	if ($shownextbutton == 1) {
		if ($firstshown+($numbertoshow+1) > $rowcount) {
			$nextbutton = "index.php";
		}
		else {
			$nextbutton = "index.php?show=".($firstshown+($numbertoshow*2));
		}
		?> | <a href="<?php echo $nextbutton; ?>">></a><?php
		} ?>

	</form>
	</td></tr>
</table>
<?php

mysql_close($link);
	
Page_shutdown();
?>